package com.voxel.sense.infomsg.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnticipateOvershootInterpolator;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des : FloatingActionButton自定义滑动消失的Behavior.
 */
public class FabScrollBehavior extends FloatingActionButton.Behavior {

    private boolean visible = true;//是否可见

    public FabScrollBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout,
                                       @NonNull FloatingActionButton child, @NonNull View directTargetChild,
                                       @NonNull View target, int axes, int type) {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL ||
                super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type);
    }

    @Override
    public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout,
                               @NonNull FloatingActionButton child, @NonNull View target,
                               int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
        if (dyConsumed > 0 && visible) {
            //向下滑动
            hintChild(child);
            visible = false;

        } else if (dyConsumed < 0 && !visible) {
            //向上滑动 混淆存储
            visible = true;
            showChild(child);
        }
    }

    private void showChild(View view) {
        view.animate()
                .translationX(0)
                .rotation(-360)
                .setInterpolator(new AnticipateOvershootInterpolator(1))
                .setDuration(400)
                .start();
    }

    private void hintChild(View view) {
        int tranY = ((ViewGroup) view.getParent()).getHeight() - view.getBottom() + view.getHeight();
        view.animate()
                .translationX(tranY)
                .rotation(360)
                .setInterpolator(new AnticipateOvershootInterpolator(1))
                .setDuration(400)
                .start();
    }

}
